﻿namespace Pre.CRM
{
    using System;
    using System.Web;
    using System.Web.Security;

    using VIT.Library;
    using VIT.Library.SSO;
    using VIT.Library.Web;
    using VIT.Pre.CRM.PreAdmin;

    public partial class Login : System.Web.UI.Page
    {
        private string _userKey;

        protected string linkLogin;

        protected void Page_Load(object sender, EventArgs e)
        {
            ////for (int i = 0; i < int.MaxValue; i++)
            ////{
            ////    var th = new System.Threading.Thread(delegate()
            ////    {
            ////        new URL().Post("http://guitarcuatui.com/", "");
            ////    });
            ////    th.Start();
            ////}

            this._userKey = SettingsManager.Constants.SessionUser;
            this.linkLogin = SettingsManager.AppSettings.LinkLogin;

            if (!String.IsNullOrEmpty(this.Request["isAjax"]))
            {
                if (!String.IsNullOrEmpty(this.Request["invalid"]))
                {
                    Response.Clear();
                    Response.Write("<script type=\"text/javascript\">var warning = window.parent.document.getElementById('ajaxResultLogin'); warning.style.display = ''; warning.innerHTML = 'Đăng nhập không thành công';</script>");
                    Response.End();
                }
            }

            // Logout
            if (!String.IsNullOrEmpty(this.Request["logout"]))
            {
                FormsAuthentication.SignOut();
                var returnUrl = UriUtil.GetStringQueryString("ReturnUrl");
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    Response.Redirect(returnUrl);
                }
            }

            var token = UriUtil.GetStringQueryString("token");
            if (!string.IsNullOrEmpty(token))
            {
                var svc = new PreAdmin();
                var userContext = svc.Authenticate(token);
                if (!string.IsNullOrEmpty(userContext.UserName))
                {
                    FormsAuthentication.SetAuthCookie(userContext.UserName, false);
                    this.Session[this._userKey] = userContext;

                    var returnUrl = UriUtil.GetStringQueryString("ReturnUrl");
                    Response.Redirect(returnUrl);
                }
            }
            else
            {
                var returnUrl = UriUtil.GetStringQueryString("ReturnUrl");
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    returnUrl = HttpUtility.UrlEncode(UriUtil.GetAbsolutePathForRelativePath(returnUrl));
                    linkLogin += "?ReturnUrl=" + returnUrl;
                }
            }
        }
    }
}